package com.shuoyue.adven.main.bussiness;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.danikula.videocache.HttpProxyCacheServer;
import com.dueeeke.videoplayer.player.VideoView;
import com.shuoyue.adven.Constant;
import com.shuoyue.adven.R;
import com.shuoyue.adven.cache.ProxyVideoCacheManager;
import com.shuoyue.adven.entity.Adv;
import com.shuoyue.adven.entity.ImpotentResult;
import com.shuoyue.adven.entity.Property;
import com.sm.appbase.base.basemvp.BaseMvpFragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;

public class FragmentProperty extends BaseMvpFragment<MainContract.Presenter> implements MainContract.View {
    Handler handlerScroll;
    Runnable scrolltask;
    protected List<Adv> mVideos = new ArrayList<>();
    public PropertyAdapter mGalleryAdapter;
    @BindView(R.id.imgs_pager)
    public ViewPager imgsPager;
    @BindView(R.id.videoView)
    public VideoView mVideoView;
    @BindView(R.id.adv_name)
    public TextView adv_name;
    @BindView(R.id.adv_contact)
    public TextView adv_contact;
    Runnable netTask;
    Handler handler;

    @Override
    public void initParams(Bundle bundle) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.sub_display;
    }

    @Override
    protected void initView() {
        mVideoView.setEnableAudioFocus(false);
        mVideoView.setOnStateChangeListener(new VideoView.SimpleOnStateChangeListener() {
            @Override
            public void onPlayStateChanged(int playState) {
                Log.e("SubVideoState", playState + "");
                //监听VideoViewManager释放，重置状态
                if (playState == VideoView.STATE_IDLE) {
                    mVideoView.release();
                } else if (playState == VideoView.STATE_ERROR || playState == VideoView.STATE_PLAYBACK_COMPLETED) {
                    startScroll();
                    mVideoView.release();
                    mVideoView.setVisibility(View.INVISIBLE);
                }
            }
        });
        mGalleryAdapter = new PropertyAdapter(mContext, mVideos);
        imgsPager.setAdapter(mGalleryAdapter);
        handlerScroll = new Handler();
        scrolltask = new Runnable() {
            @Override
            public void run() {
                handlerScroll.postDelayed(this, Constant.SUB_SCREEN_SCROLL_DELAY);
                if (imgsPager != null)
                    imgsPager.setCurrentItem(imgsPager.getCurrentItem() + 1);
            }
        };

        mGalleryAdapter.setImgScaleType(ImageView.ScaleType.CENTER_INSIDE);
        imgsPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Log.e("xxxxxx", imgsPager.getHeight() + "");
                if (mVideos.size() == 0)
                    return;
                Adv adv = mVideos.get(position % mVideos.size());
//                activity.uploadShowInfo(adv.getId()); TODO
                if (adv.getType() == adv.TYPE_VIDEO) {
                    startPlay(position);
                } else {
                    mVideoView.release();
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        startScroll();
    }

    @Override
    public void initData() {
        mPresenter = new MainContract.Presenter();
        mPresenter.attachView(this);
        initTimerTask();
    }

    void initTimerTask() {
        handler = new Handler();
        netTask = () -> {
            handler.postDelayed(netTask, Constant.NET_TASK * 1000);
            Log.e("任务：", "网络任务");
            doNetTask();
        };
        handler.post(netTask);
    }

    void doNetTask() {
        mPresenter.queryPropertyAdv();
        mPresenter.getPropertyInfo();
    }

    /**
     * 开始播放
     *
     * @param position 列表位置
     */
    protected void startPlay(int position) {
        stopScroll();
        Log.e("method", "startPlay");
        mVideoView.setVisibility(View.VISIBLE);
        Adv videoBean = mVideos.get(position % mVideos.size());
        HttpProxyCacheServer cacheServer = ProxyVideoCacheManager.getProxy(mContext);
        String proxyUrl = cacheServer.getProxyUrl(videoBean.getVideoUrl());
        mVideoView.setUrl(proxyUrl);
        mVideoView.setUrl(proxyUrl);
        mVideoView.release();
        mVideoView.start();

    }

    @Override
    public void onStop() {
        super.onStop();
        if (mVideoView != null) {
            mVideoView.release();
        }
    }

    void startScroll() {
        handlerScroll.postDelayed(scrolltask, Constant.SUB_SCREEN_SCROLL_DELAY);
    }

    void stopScroll() {
        handlerScroll.removeCallbacks(scrolltask);
    }


    //<editor-folder desc="开放给Activity的方法">


    public void setPropertyInfo(Property propertyInfo) {

    }


    @Override
    public void queryBusinessAdvSuc(List<Adv> mData) {

    }

    @Override
    public void queryPropertyAdvSuc(List<Adv> videoList) {
        if (mGalleryAdapter == null) {
            mGalleryAdapter = new PropertyAdapter(mContext, null);
        }
        mVideos.clear();
        mVideos.addAll(videoList);

        if (videoList.size() > 1) {
            startScroll();
        } else {
            stopScroll();
        }
    }

    @Override
    public void queryImpotentAdvSuc(ImpotentResult mdata) {
    }

    @Override
    public void getPropertyInfoSuc(Property propertyInfo) {
        adv_name.setText(propertyInfo.getTitle());
        adv_contact.setText("物业电话：" + propertyInfo.getLinkphone());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mVideoView != null) {
            mVideoView.release();
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
    }
}
